﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LBKDHelper.Models;
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace LM.CB.K3Cloud.Plugin
{
    [Description("自定义费用分配标准值维护表单插件"), HotUpdate]
    public class AllocStandardData : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 核算组织
        /// </summary>
        readonly ElementKeySchema FACCTGORGID = new ElementKeySchema
        {
            FormKey = "FACCTGORGID",
            DbKey = "FACCTGORGID",
            OrmKey = "ACCTGORGID"
        };

        /// <summary>
        /// 会计期间
        /// </summary>
        readonly ElementKeySchema FShowPeriod = new ElementKeySchema
        {
            FormKey = "FShowPeriod",
            OrmKey = "ShowPeriod"
        };

        /// <summary>
        /// 分录
        /// </summary>
        readonly ElementKeySchema FEntity = new ElementKeySchema
        {
            FormKey = "FEntity",
            DbKey = "T_CB_ALLOCSTANDARDDATAENTRY",
            OrmKey = "CB_ALLOCSTANDARDDATAENTRY"
        };

        /// <summary>
        /// 作业活动
        /// </summary>
        readonly ElementKeySchema FWORKACTIVEID = new ElementKeySchema
        {
            FormKey = "FWORKACTIVEID",
            DbKey = "FWORKACTIVEID",
            OrmKey = "WORKACTIVEID"
        };

        /// <summary>
        /// 成本中心编码
        /// </summary>
        readonly ElementKeySchema FCOSTCENTERID = new ElementKeySchema
        {
            FormKey = "FCOSTCENTERID",
            DbKey = "FCOSTCENTERID",
            OrmKey = "COSTCENTERID"
        };

        /// <summary>
        /// 数量
        /// </summary>
        readonly ElementKeySchema FQTY = new ElementKeySchema
        {
            FormKey = "FQTY",
            DbKey = "FQTY",
            OrmKey = "QTY"
        };

        /// <summary>
        /// 业务类型
        /// </summary>
        readonly ElementKeySchema FPROORDERTYPE = new ElementKeySchema
        {
            FormKey = "FPROORDERTYPE",
            DbKey = "FPROORDERTYPE",
            OrmKey = "PROORDERTYPE"
        };

        /// <summary>
        /// 订单编号
        /// </summary>
        readonly ElementKeySchema FPROORDERID = new ElementKeySchema
        {
            FormKey = "FPROORDERID",
            DbKey = "FPROORDERID",
            OrmKey = "PROORDERID"
        };

        /// <summary>
        /// 生产订单分录内码
        /// </summary>
        readonly ElementKeySchema FPROORDERENTRYID = new ElementKeySchema
        {
            FormKey = "FPROORDERENTRYID",
            DbKey = "FPROORDERENTRYID",
            OrmKey = "FPROORDERENTRYID"
        };

        /// <summary>
        /// 订单行号
        /// </summary>
        readonly ElementKeySchema FPROORDERSEQ = new ElementKeySchema
        {
            FormKey = "FPROORDERSEQ",
            DbKey = "FPROORDERSEQ",
            OrmKey = "FPROORDERSEQ"
        };

        /// <summary>
        /// 产品编码
        /// </summary>
        readonly ElementKeySchema FPRODUCTID = new ElementKeySchema
        {
            FormKey = "FPRODUCTID",
            DbKey = "FPRODUCTID",
            OrmKey = "PRODUCTID"
        };

        /// <summary>
        /// 生产车间
        /// </summary>
        readonly ElementKeySchema FWORKSHOPID = new ElementKeySchema
        {
            FormKey = "FWORKSHOPID",
            DbKey = "FWORKSHOPID",
            OrmKey = "FWORKSHOPID"
        };

        /// <summary>
        /// 分配标准
        /// </summary>
        readonly ElementKeySchema FSTANDARDID = new ElementKeySchema
        {
            FormKey = "FSTANDARDID",
            DbKey = "FSTANDARDID",
            OrmKey = "STANDARDID"
        };

        /// <summary>
        /// 工行编号文本
        /// </summary>
        readonly ElementKeySchema FPROORDERNO = new ElementKeySchema
        {
            FormKey = "FPROORDERNO",
            DbKey = "FPROORDERNO",
            OrmKey = "PROORDERNO"
        };

        #endregion

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            if ("DEV_tbGETJBCJZY".Equals(e.BarItemKey))
            {
                GetData(e);
            }
        }

        private void GetData(BarItemClickEventArgs e)
        {
            // 清空老数据
            View.Model.DeleteEntryData(FEntity.FormKey);

            var org = Model.GetValue(FACCTGORGID.FormKey) as DynamicObject;
            string orgId = Convert.ToString(org["Id"]);
            var ym = View.Model.GetValue(FShowPeriod.FormKey)?.ToString() ?? "";
            MatchCollection ymMatches = Regex.Matches(ym, @"\d+");
            string year = ymMatches[0].Value;
            string period = ymMatches[1].Value;

            var sql = $@"/*dialect*/
            with 成本中心 as (
	            select *
	            from T_CB_COSTCENTER
	            where FBUSINESSTYPE = 4-- 基本生产
            -- 	and FUSEORGID = @org
            )
            , 单据类型 as (
	            select a.FBILLTYPEID, b.FNAME as '单据类型名称'
	            from T_BAS_BILLTYPE as a
	            inner join T_BAS_BILLTYPE_L as b on b.FLOCALEID = 2052 and b.FBILLTYPEID = a.FBILLTYPEID
            )
            , 生产订单工艺路线 as (
	            select FEntryId as '生产订单分录内码', F_QLTK_COSTCENTER as '工艺路线成本中心内码'
		            , F_QLTK_ZYHD as '作业活动内码', '实际耗用量' = sum(F_QLTK_QTY)
	            from QLTK_t_Route-- 生产订单工艺路线表
	            group by FEntryId, F_QLTK_COSTCENTER, F_QLTK_ZYHD
	            having F_QLTK_ZYHD > 0
            )
            , 生产订单工艺路线Plus as (
	            select a.生产订单分录内码, b.FSEQ as '生产订单分录行号', c.FBILLNO as '生产订单编号'
		            , d.单据类型名称 as '生产订单类型名称', e.FNUMBER as '产品编码', a.工艺路线成本中心内码
		            , a.实际耗用量, b.FMATERIALID as '产品内码', h.FCOSTCENTERID as '生产车间成本中心内码'
		            , '产品数量' = isnull(f.F_DEV_CPSL, 1), c.FPRDORGID as '生产组织内码'
		            , i.F_QLTK_FYFPBZ as '作业活动分配标准内码', '业务类型' = 'PO'-- 普通生产
		            , b.FWORKSHOPID as '生产车间内码', g.FENTRYID as '生产订单单据资料内码', a.作业活动内码
	            from 生产订单工艺路线 as a
	            inner join T_PRD_MOENTRY as b on b.FENTRYID = a.生产订单分录内码
	            inner join T_PRD_MO as c on c.FID = b.FID
	            inner join 单据类型 as d on d.FBILLTYPEID = c.FBILLTYPE
	            inner join T_BD_MATERIAL as e on e.FMATERIALID = b.FMATERIALID
	            left join DEV_t_ProcessRoute as f on f.FID = b.FROUTINGID-- 工艺路线头表
	            inner join T_CB_PROORDERTYPE as g on g.FFORMID = 'PRD_MO' and g.FPROORDERENTRYID = b.FENTRYID
	            inner join T_CB_COSTCENTER as h on h.FRELATIONTYPE = 'BD_Department' and h.FRELATION = b.FWORKSHOPID
	            inner join T_CB_WORKACTIVITIES as i on i.FWORKACTIVEID = a.作业活动内码
	            where i.F_QLTK_FYFPBZ > 0
            )
            , 生产入库单 as (
	            select a.FSID as '生产订单分录内码', d.FBASEPRDREALQTY as '入库数量'
                    , '入库年份' = year(c.FDATE), '入库月份' = month(c.FDATE)
                from T_PRD_INSTOCKENTRY_LK as a
                inner join T_PRD_INSTOCKENTRY as b on b.FENTRYID = a.FENTRYID
                inner join T_PRD_INSTOCK as c on c.FID = b.FID
                inner join T_PRD_INSTOCKENTRY_A as d on d.FENTRYID = b.FENTRYID
                where a.FSTABLENAME = 'T_PRD_MOENTRY'
            )
            , 总表 as (
	            select a.生产车间成本中心内码, a.作业活动分配标准内码, a.作业活动内码, a.生产车间内码
		            , '数量' = a.实际耗用量 / a.产品数量 * c.入库数量, a.生产订单编号
		            , a.业务类型, a.生产订单类型名称, a.生产订单分录行号, a.产品编码, a.生产订单分录内码
		            , a.产品内码, a.生产订单单据资料内码
	            from 生产订单工艺路线Plus as a
	            inner join 成本中心 as b on b.FCOSTCENTERID = a.工艺路线成本中心内码
	            inner join 生产入库单 as c on c.生产订单分录内码 = a.生产订单分录内码
	            where 1 = 1
                and a.生产组织内码 = {orgId}
                and c.入库年份 = {year} and c.入库月份 = {period}
	            and 1 = 1
            )
            select 
	            作业活动分配标准内码,
	            生产订单分录内码,
	            sum(数量) as 数量,
	            max(生产车间成本中心内码) as 生产车间成本中心内码,
	            max(作业活动内码) as 作业活动内码,
	            max(生产车间内码) as 生产车间内码,
	            max(业务类型) as 业务类型,
	            max(生产订单类型名称) as 生产订单类型名称,
	            max(生产订单分录行号) as 生产订单分录行号,
	            max(产品编码) as 产品编码,
	            max(产品内码) as 产品内码,
	            max(生产订单单据资料内码) as 生产订单单据资料内码,
	            max(生产订单编号) as 生产订单编号
            from 总表
            where 数量 > 0
            group by 
	            作业活动分配标准内码,
	            生产订单分录内码;";

            var dataCollection = DBUtils.ExecuteDynamicObject(Context, sql);
            var entity = View.BusinessInfo.GetEntity(FEntity.FormKey);
            for (int i = 0, l = dataCollection?.Count ?? 0; i < l; i++)
            {
                var dataItem = dataCollection[i];

                Model.CreateNewEntryRow(entity, i);

                //var activeId = Convert.ToInt32(dataItem["作业活动内码"]);
                //View.Model.SetItemValueByID(FWORKACTIVEID.FormKey, activeId, i);

                // 成本中心
                var costCenterId = Convert.ToInt32(dataItem["生产车间成本中心内码"]);
                View.Model.SetItemValueByID(FCOSTCENTERID.FormKey, costCenterId, i);

                var workshopId = Convert.ToInt32(dataItem["生产车间内码"]);
                View.Model.SetItemValueByID(FWORKSHOPID.FormKey, workshopId, i);

                // 数量
                var qty = Convert.ToDouble(dataItem["数量"]);
                View.Model.SetValue(FQTY.FormKey, qty, i);

                // 业务类型
                var bizType = Convert.ToString(dataItem["业务类型"]);
                View.Model.SetValue(FPROORDERTYPE.FormKey, bizType, i);

                var entryId = Convert.ToInt32(dataItem["生产订单分录内码"]);
                View.Model.SetItemValueByID(FPROORDERENTRYID.FormKey, entryId, i);

                var billInfoId = Convert.ToString(dataItem["生产订单单据资料内码"]);
                View.Model.SetItemValueByID(FPROORDERID.FormKey, billInfoId, i);

                var entrySeq = Convert.ToInt32(dataItem["生产订单分录行号"]);
                View.Model.SetItemValueByID(FPROORDERSEQ.FormKey, entrySeq, i);

                var productId = Convert.ToInt32(dataItem["产品内码"]);
                View.Model.SetItemValueByID(FPRODUCTID.FormKey, productId, i);

                var standardId = Convert.ToInt32(dataItem["作业活动分配标准内码"]);
                View.Model.SetItemValueByID(FSTANDARDID.FormKey, standardId, i);

                var billNo = Convert.ToString(dataItem["生产订单编号"]);
                View.Model.SetItemValueByID(FPROORDERNO.FormKey, billNo, i);
            }

            View.UpdateView(FEntity.FormKey);
        }
    }
}
